import error
import random
from dependencies.myMySQL.mysqDB import MySQLOrm

from concurrent.futures import ThreadPoolExecutor
from sql.warehouseInventory import *
from dependencies.myRabbitmq.rabbitConsumer import RabbitConsumer
from dependencies.myRabbitmq.rabbitPublish import RabbitPublisher
from dependencies.myRabbitmq.amqpUtil import AMQPUtil
from utils import *

from inventory.online import execute_insert_goods_sku_batch
from inventory.orderInlay import execute_insert_order_inlay
from inventory.selfInlay import execute_insert_self_inlay

mysql = MySQLOrm()
execute = ThreadPoolExecutor()


# 接收java端 盘库发起请求
def create(params):
    """
     1.生成一条发起任务（数据库）
     2.创建一个延时任务（rabbitmq）
    :param params:   createBy createAt executeTime  (要执行的时间)
    :return:
    """
    if params['warehouseId'] == '':
        raise error.MyError(error.ErrorCode.INVALID_PARAMS_NONE.format('warehouseId'))
    if params['executeTime'] == '':
        raise error.MyError(error.ErrorCode.INVALID_PARAMS_NONE.format('executeTime'))
    if params['createBy'] == '':
        raise error.MyError(error.ErrorCode.INVALID_PARAMS_NONE.format('createBy'))
    if params['createAt'] == '':
        raise error.MyError(error.ErrorCode.INVALID_PARAMS_NONE.format('createAt'))

    _table = str(get_consumer_now__format('%Y%m%d')) + '_' + str(params['warehouseId'])
    # sql 信息组装
    insert_params = (
        params['warehouseId'],
        params['executeTime'],
        params['createBy'],
        params['createAt'],
        _table
    )
    insertId = mysql.insert_common(INSERT_INTO, insert_params)
    # routing_key, msg, exchange, [delay=None, TTL=None 开启延时消息]
    msg1 = str({"insertId": insertId, "warehouseId": params['warehouseId']})
    RabbitPublisher.run("test_{0}_{1}_{2}".format(_table, insertId, random.randint(0, 9)), msg1, 'test', True,
                        get_contrast_time(params['executeTime']))
    execute.submit(RabbitConsumer.run, "RetryQueue", callback)

    return "success"


# mq 回调消息
def callback(ch, method, properties, body):
    # 获取盘库任务id
    callBackBody = eval(body.decode())
    # 盘库任务id
    warehouseInventoryId = callBackBody["insertId"]
    # 仓库id
    warehouseId = callBackBody["warehouseId"]
    # 如果处理成功，则调用此消息回复ack，表示消息成功处理完成。
    AMQPUtil.message_handle_successfully(ch, method)
    #  回调成功执行 商品导入操作
    """
        1.商品sku库存导入操作(根据仓库id)
        2.客订镶嵌库存导入操作
        3.自留镶嵌库存导入操作
    """

    try:
        execute_insert_goods_sku_batch(warehouseId)
        execute_insert_order_inlay()
        execute_insert_self_inlay()
        """ 修改任务状态 2=执行成功"""
        if mysql.update_common(UPDATE_STATUS, (2, warehouseInventoryId)) == 1:
            print("修改数据记录状态成功")
        else:
            print("警告！！！！！修改数据记录状态失败")

    except Exception as e:
        """ 修改任务状态 3=执行失败"""
        mysql.update_common(UPDATE_STATUS, (3, warehouseInventoryId))
        raise error.MyError(e)
